import { Filter } from "mongodb"
import { db } from "../db"
import { FetchAPI, PageParams, Pager, AccessLog } from '../interface'
import { logger } from "f2e-server3"

const CONN_NAME = 'illegal_access_logs'
export const log_list: FetchAPI<PageParams<Filter<AccessLog>>, Pager<AccessLog>> = async (body) => {
    const { page = 1, pageSize = 10, params = {} } = body || {}
    const conn = db.collection<AccessLog>(CONN_NAME)
    const total = await conn.countDocuments(params)
    const list = await conn.find(params).skip((page - 1) * pageSize).limit(pageSize).toArray()
    return {
        success: true,
        data: {
            list,
            total,
            page,
            pageSize,
        }
    }
}

export const log_list_add: FetchAPI<AccessLog, AccessLog> = async (body, ctx) => {
    const conn = db.collection<AccessLog>(CONN_NAME)
    const createdBy = ctx?.loginUser?.username
    const log: AccessLog = {
        ...body,
        createdAt: new Date(),
        createdBy,
    }
    const res = await conn.insertOne(log)
    logger.info('illegal_access_logs add:', JSON.stringify(body))

    return {
        success: true,
        data: {
            ...log,
            _id: res.insertedId,
        }
    }
}
